package com.cskaoyan.app.service.impl;

import com.cskaoyan.app.bean.bo.adminbo.AdminAdminBo;
import com.cskaoyan.app.bean.bo.adminbo.AdminDelBo;
import com.cskaoyan.app.bean.common.BasePageInfo;
import com.cskaoyan.app.bean.po.MarketAdmin;
import com.cskaoyan.app.bean.po.MarketAdminExample;
import com.cskaoyan.app.config.AliComponent;
import com.cskaoyan.app.controller.AdminAdminController;
import com.cskaoyan.app.mapper.MarketAdminMapper;
import com.cskaoyan.app.service.AdminAdminService;
import com.cskaoyan.app.util.EncryptUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author kiggy
 * @since 2022/12/28 23:03
 */
@Service
@MultipartConfig
public class AdminAdminServiceImpl implements AdminAdminService {

    @Value("${spring.web.resources.static-locations}")
    private String filePath;

    @Autowired
    MarketAdminMapper adminMapper;

    @Autowired
    AliComponent aliComponent;

    @Override
    public PageInfo<MarketAdmin> listPageAdmins(BasePageInfo basePageInfo) {
        PageHelper.startPage(basePageInfo.getPage(), basePageInfo.getLimit());

        MarketAdminExample marketAdminExample = new MarketAdminExample();
        MarketAdminExample.Criteria criteria = marketAdminExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        marketAdminExample.setOrderByClause(basePageInfo.getSort() + " " + basePageInfo.getOrder());
        List<MarketAdmin> marketAdmins = adminMapper.selectByExample(marketAdminExample);

        PageInfo<MarketAdmin> marketAdminPageInfo = new PageInfo<>(marketAdmins);

        return marketAdminPageInfo;
    }


    /**
     * @param adminBo
     * @return
     */
    @Override
    public MarketAdmin update(AdminAdminBo adminBo) {
        MarketAdminExample marketAdminExample = new MarketAdminExample();
        MarketAdminExample.Criteria criteria = marketAdminExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        criteria.andIdEqualTo(adminBo.getId());
        MarketAdmin marketAdmin = new MarketAdmin();

        // 为marketAdmin赋值
        marketAdmin.setId(adminBo.getId());
        marketAdmin.setUsername(adminBo.getUsername());
        marketAdmin.setAvatar(adminBo.getAvatar());
        marketAdmin.setUpdateTime(new Date());
        marketAdmin.setRoleIds(adminBo.getRoleIds());
        marketAdmin.setPassword(adminBo.getPassword());

        // 更新marketAdmin
        adminMapper.updateByExampleSelective(marketAdmin, marketAdminExample);
        marketAdmin.setPassword(null);
        return marketAdmin;
    }

    /**
     * 逻辑删除
     * TODO:本质是更新，不需要判定字符串是否为空，应该把所有字符串取出来，再赋值
     *
     * @param adminDelBo
     */
    @Override
    @Transactional
    public void delAdminData(AdminDelBo adminDelBo) {
        // 先取出
        MarketAdmin marketAdmin = adminMapper.selectByPrimaryKey(adminDelBo.getId());
        // 再删除
        marketAdmin.setDeleted(true);
        adminMapper.updateByPrimaryKeySelective(marketAdmin);
    }

    /**
     * 将文件上传到阿里云服务器上，获得其url
     *
     * @param file
     */
    @Override
    public String aliFileUpload(MultipartFile file) {
        String url = "";
        try {
            InputStream inputStream = file.getInputStream();
            String name = file.getOriginalFilename();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
            String fileName = dateFormat.format(new Date()) + "." + name.substring(name.lastIndexOf(".") + 1);
            aliComponent.fileUpload(fileName, inputStream);
            url = aliComponent.getUrl(fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return url;
    }

    /**
     * 将文件下载在本地的方式上传图片
     * @param request
     */
    @Override
    public void createPicFile(HttpServletRequest request) {
        try {
            // 通配文件名
            Part file = request.getPart("file");
            String fileType = file.getContentType();
            String fileName = UUID.randomUUID().toString();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
            Date date = new Date();
            String format = dateFormat.format(date);
            fileName += format + "." + fileType;

            // 获得其路径
            String replace = filePath.replace("file:", "");

            // File file = new File(replace+fileName);
            File newFile = new File(replace + fileName);
            if (newFile.exists()) {
                newFile.getParentFile().mkdirs();
            }
            newFile.createNewFile();

            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            InputStream inputStream = file.getInputStream();
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ServletException e) {
            e.printStackTrace();
        }
    }

    /**
     * 校验用户名是否重复
     * 将数据添加进数据库，id,username,password,avatar,add_time,update_time,deleted,roleIds[]
     * 返回数据
     *
     * @param createBo
     * @return
     */
    @Override
    @Transactional
    public List<MarketAdmin> createAdminData(AdminAdminBo createBo) {
        // 判断用户名是否重复
        MarketAdminExample adminExample = new MarketAdminExample();
        MarketAdminExample.Criteria criteria = adminExample.createCriteria();
        criteria.andUsernameEqualTo(createBo.getUsername());
        List<MarketAdmin> admins = adminMapper.selectByExample(adminExample);
        if (admins.size() != 0) {
            return null;
        }
        MarketAdmin marketAdmin = new MarketAdmin();
        // 新增——>取出最后添加
        marketAdmin.setUsername(createBo.getUsername());
        marketAdmin.setPassword(EncryptUtil.encrypt(createBo.getPassword()));
        marketAdmin.setAddTime(new Date());
        marketAdmin.setRoleIds(createBo.getRoleIds());
        marketAdmin.setUpdateTime(new Date());
        marketAdmin.setDeleted(false);
        marketAdmin.setAvatar(createBo.getAvatar());
        adminMapper.insert(marketAdmin);
        // 取出
        PageHelper.startPage(1, 1);
        MarketAdminExample marketAdminExample = new MarketAdminExample();
        marketAdminExample.setOrderByClause("add_time desc");
        List<MarketAdmin> marketAdmins = adminMapper.selectByExample(marketAdminExample);
        PageInfo<MarketAdmin> marketAdminPageInfo = new PageInfo<>(marketAdmins);
        List<MarketAdmin> list = marketAdminPageInfo.getList();
        return list;
    }

}
